<template>
  <div ref="chartRef" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from 'echarts';

const chartsArr = []

// echart
export default {
  name: 'BaseChart',
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '308px'
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // 实例对象id
      instanceId: ''
    }
  },
  watch: {
    options: {
      handler() {
        this.updateChart()
      },
      deep: true
    }
  },
  mounted() {
    this.initCharts()
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    // 移除窗口resize事件
    window.removeEventListener('resize', this.resizeCharts)
  },
  methods: {
    initCharts() {
      const chart1 = echarts.init(this.$refs.chartRef)
      chart1.setOption(this.options)
      chartsArr.push(chart1)
      this.instanceId = chart1.id
    },
    updateChart() {
      const target = chartsArr.find(v => v.id === this.instanceId)
      if (target) {
        // 清空画布
        target.clear()
        // 解决echart宽高动态设置的情况下显示异常
        target.resize()
        // 重新设置配置项
        target.setOption(this.options)
      }
    },
    resizeCharts() {
      for (var i = 0; i < chartsArr.length; i++) {
        chartsArr[i] && chartsArr[i].resize()
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
